<script lang="ts" setup>
import type { UserCenterGetParams2 } from '@/service/app/types'
import { userCenterGet2 } from '@/service/app/userCenter'

defineOptions({
  name: 'HomeProducts',
})

const props = defineProps<Props>()

interface Props {
  categoryName: string
  isPopular: boolean
}

// 产品列表参数
const productListParams = ref<UserCenterGetParams2>({
  'condition.page': 1,
  'condition.size': 10,
  'condition.category': '',
  'condition.isPopular': true,
  'condition.keyword': '',
})

// 产品列表数据
const productList = ref<any[]>([])
const currentPage = ref(1)
const hasMore = ref(true)
const isLoading = ref(false)
const isError = ref(false)

// 监听分类变化，重置数据
watch(
  () => [props.categoryName, props.isPopular],
  ([categoryName, isPopular]) => {
    // 重置状态
    productList.value = []
    currentPage.value = 1
    hasMore.value = true
    isError.value = false

    // 更新查询参数
    productListParams.value = {
      'condition.page': 1,
      'condition.size': 10,
      'condition.category': String(categoryName),
      'condition.isPopular': Boolean(isPopular),
      'condition.keyword': '',
    }

    // 加载第一页数据
    loadMoreProducts()
  },
  { immediate: true },
)

// 加载更多产品
async function loadMoreProducts() {
  if (isLoading.value || !hasMore.value)
    return

  isLoading.value = true
  isError.value = false

  try {
    const result = await userCenterGet2({
      params: {
        ...productListParams.value,
        'condition.page': currentPage.value,
      },
    })

    const newProducts = result?.data?.data || []

    if (currentPage.value === 1) {
      // 第一页，直接替换
      productList.value = newProducts
    }
    else {
      // 后续页，追加到列表
      productList.value.push(...newProducts)
    }

    // 检查是否还有更多数据
    hasMore.value = newProducts.length === productListParams.value['condition.size']

    if (hasMore.value) {
      currentPage.value++
    }
  }
  catch (error) {
    console.error('加载产品失败:', error)
    isError.value = true
  }
  finally {
    isLoading.value = false
  }
}

// 页面触底事件
onReachBottom(() => {
  if (hasMore.value && !isLoading.value) {
    loadMoreProducts()
  }
})

// 图片错误状态管理
const imgErrorMap = ref<Record<string, boolean>>({})

// 获取完整图片URL
function getFullImageUrl(relativePath: string) {
  if (!relativePath)
    return '/static/images/default-avatar.png'
  if (relativePath.startsWith('http'))
    return relativePath
  const ossBaseUrl = 'https://oss.tz-group.com/'
  const cleanPath = relativePath.startsWith('/') ? relativePath.slice(1) : relativePath
  return `${ossBaseUrl}${cleanPath}`
}

// 处理图片加载错误
function handleImageError(productId: string | number) {
  imgErrorMap.value[productId] = true
  console.log('图片加载失败，产品ID:', productId)
}

// 跳转到产品详情页
function goToProductDetail(product: any) {
  if (!product) {
    uni.showToast({
      title: '产品数据无效',
      icon: 'error',
    })
    return
  }

  // 获取产品ID
  const actualId = product.productId || product.id || product.product_id

  if (!actualId || actualId === 0) {
    uni.showToast({
      title: '产品ID无效',
      icon: 'error',
    })
    return
  }

  uni.navigateTo({
    url: `/pages/product-detail/index?id=${actualId}`,
  })
}
</script>

<template>
  <view class="mx-5 my-5">
    <!-- 初始加载状态 -->
    <view v-if="isLoading && productList.length === 0" class="py-8 text-center text-gray-500">
      加载中...
    </view>

    <!-- 错误状态 -->
    <view v-else-if="isError && productList.length === 0" class="py-8 text-center text-red-500">
      加载失败，请重试
    </view>

    <!-- 产品列表数据展示 -->
    <view v-else-if="productList.length > 0" class="space-y-4">
      <view
        v-for="product in productList"
        :key="product.productId"
        class="border border-gray-100 rounded-xl bg-white p-4 shadow-sm"
        @click="goToProductDetail(product)"
      >
        <view class="flex space-x-4">
          <!-- 产品图片 -->
          <view class="h-24 w-24 flex-shrink-0 overflow-hidden rounded-lg bg-gray-100">
            <image
              v-if="product.mainPhotoes?.[0]?.attachmentAddress"
              :src="getFullImageUrl(product.mainPhotoes[0].attachmentAddress)"
              class="h-full w-full"
              mode="aspectFill"
              @error="handleImageError(product.productId)"
            />
            <view
              v-else
              class="h-full w-full flex items-center justify-center text-xs text-gray-400"
            >
              暂无图片
            </view>
          </view>

          <!-- 产品信息 -->
          <view class="flex-1 space-y-2">
            <view class="mb-2 flex items-start justify-between">
              <view class="line-clamp-2 mr-2 flex-1 text-sm text-gray-800 font-medium">
                {{ product.productName }}
              </view>
              <view
                class="border border-green-400 rounded bg-green-50 px-2 py-1 text-xs text-green-500"
              >
                {{ product.coreTarget }}
              </view>
            </view>
            <view class="text-xs text-gray-500">
              品牌：{{ product.brand }}
            </view>
            <view class="text-xs text-gray-500">
              产地：{{ product.model }}
            </view>
            <view class="mb-2 text-xs text-blue-600">
              {{ product.gradeName }}
            </view>

            <!-- 等级标签组 -->
            <view class="mt-2 flex items-end space-x-2">
              <view
                v-for="gradeInfo in [
                  { grade: 'A', label: 'A', color: '#027F3F' },
                  { grade: 'B', label: 'B', color: '#68D300' },
                  { grade: 'C', label: 'C', color: '#FFB422' },
                  { grade: 'D', label: 'D', color: '#FF8738' },
                ]"
                :key="gradeInfo.grade"
                class="rounded px-3 py-1 text-sm text-white font-medium transition-all duration-200"
                :class="
                  product.grade === gradeInfo.grade
                    ? 'scale-125 shadow-lg border-2 border-white'
                    : 'opacity-60'
                "
                :style="{
                  backgroundColor: gradeInfo.color,
                  transform: 'skewX(12deg)',
                  height: product.grade === gradeInfo.grade ? '32px' : '24px',
                  lineHeight: product.grade === gradeInfo.grade ? '32px' : '24px',
                  zIndex: product.grade === gradeInfo.grade ? '10' : '1',
                }"
              >
                <text class="inline-block transform -skew-x-12">
                  {{ gradeInfo.label }}
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 产品列表空状态 -->
    <view v-else class="py-8 text-center text-gray-500">
      暂无产品
    </view>

    <!-- 加载更多状态 -->
    <view v-if="productList.length > 0" class="py-4 text-center">
      <view v-if="isLoading" class="text-gray-500">
        加载中...
      </view>
      <view v-else-if="!hasMore" class="text-sm text-gray-400">
        没有更多了
      </view>
      <view v-else-if="isError" class="text-sm text-red-500" @click="loadMoreProducts">
        加载失败，点击重试
      </view>
    </view>
  </view>
</template>
